<?php

/**
 * @author Nguyen Thai Binh
 */
class Auth {

  var $CI;

  function Auth() {
    $this->CI = & get_instance();
  }

  function is_login() {
    $session_login = $this->CI->config->item('session_login');
    foreach ($session_login as $session) {
      if (userdata($session) == '')
        return FALSE;
    }
    return TRUE;
  }
  
  function grant_role($role){
    return $role == userdata('role');
  }

  function get_user_login($iden_field = '') {
    if ($this->is_login()) {
      $conditions = array();
      if (empty($iden_field)) {
        $iden_field = $this->CI->config->item('session_login');
        foreach ($iden_field as $field) {
          $conditions[$field] = userdata($field);
        }
      }
      if (!empty($conditions)) {
        return $this->CI->user_model->get($conditions);
      }
    }
    return NULL;
  }

  function generateActiveCode($word, $space = false) {
    if ($space) {
      $pool = '0123456789abcdefghijklmnopqrstuvwxyzQAZWSXEDCRFVTGBYHNUJMIKOLP ';
    } else {
      $pool = '0123456789abcdefghijklmnopqrstuvwxyzQAZWSXEDCRFVTGBYHNUJMIKOLP';
    }
    $str = '';
    for ($i = 0; $i < $word; $i++) {
      $str .= substr($pool, mt_rand(0, strlen($pool) - 1), 1);
    }
    return $str;
  }

  function generateNumberic($word) {
    $pool = '0123456789';
    $str = '';
    for ($i = 0; $i < $word; $i++) {
      $str .= substr($pool, mt_rand(0, strlen($pool) - 1), 1);
    }
    return $str;
  }

  function loginFromCode($id) {
    $checkUser = $this->CI->user_model->get($id);
    if ($checkUser != NULL) {
      $this->session_login($checkUser);
    }
  }

  function session_login($data) {
    $session_login = $this->CI->config->item('session_login');
    foreach ($session_login as $session) {
      set_userdata($session, $data[$session]);
    }
  }

  function session_logout() {
    $session_login = $this->CI->config->item('session_login');
    foreach ($session_login as $session) {
      unset_userdata($session);
    }
  }

  function can_access($uri) {
    return TRUE;
  }

}